package cn.ffcs.uec.outStaffLeaveApply.component;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.zkoss.zk.ui.Components;
import org.zkoss.zk.ui.Executions;
import org.zkoss.zk.ui.IdSpace;
import org.zkoss.zk.ui.SuspendNotAllowedException;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.ForwardEvent;
import org.zkoss.zul.Div;
import org.zkoss.zul.Messagebox;
import org.zkoss.zul.Window;

import cn.ffcs.raptornuke.plugin.common.zk.util.ZkUtil;
import cn.ffcs.uec.common.manager.CustomFilesManager;
import cn.ffcs.uec.common.util.NodeVoUtil;
import cn.ffcs.uec.common.util.PermissionUtil;
import cn.ffcs.uec.common.util.UecConstants;
import cn.ffcs.uec.common.vo.UecBdPsncl;
import cn.ffcs.uec.organization.manager.UecOrgDeptManager;
import cn.ffcs.uec.organization.manager.UecOrgOrgsManager;
import cn.ffcs.uec.organization.model.UecOrgDept;
import cn.ffcs.uec.organization.vo.OrganizationRelationVo;
import cn.ffcs.uec.outStaff.constant.UecOutStaffConstants;
import cn.ffcs.uec.outStaff.manager.UecOutStaffContractManager;
import cn.ffcs.uec.outStaff.model.UecOutStaffContract;
import cn.ffcs.uec.outStaff.model.UecOutStaffInfo;
import cn.ffcs.uec.outStaff.vo.UecOutStaffInfoVo;
import cn.ffcs.uec.outStaffLeaveApply.component.bean.OutStaffLeaveApplyListboxBean;
import cn.ffcs.uec.recordsApproval.constant.ApprovalConstants;
import cn.ffcs.uec.recordsApproval.util.ApprovalUtil;
import cn.ffcs.uec.staff.manager.UecPsnjobManager;
import cn.ffcs.uec.staff.manager.UecTrialManager;
import cn.ffcs.uec.staff.model.UecPsnjob;
import cn.ffcs.uec.staff.model.UecTrial;
import cn.ffcs.uom.common.constants.BaseUnitConstants;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.DateUtil;
import cn.ffcs.uom.common.util.IPortletInfoProvider;
import cn.ffcs.uom.common.util.ListboxUtils;
import cn.ffcs.uom.common.util.PlatformUtil;
import cn.ffcs.uom.common.util.PubUtil;
import cn.ffcs.uom.common.util.StrUtil;
import cn.ffcs.uom.common.vo.NodeVo;
import lombok.Getter;
import lombok.Setter;

@Controller
@Scope("prototype")
public class OutStaffLeaveApplyListboxExt extends Div implements IdSpace {

	private static final long serialVersionUID = -131257935772754497L;

	private static final String OUT_STAFF_LEAVE_APPLY_LISTBOX_EXT_ZUL = "/pages_nmg/outStaffLeaveApply/comp/outStaffLeaveApply_listbox_ext.zul";

	private OutStaffLeaveApplyListboxBean bean = new OutStaffLeaveApplyListboxBean();

	private UecTrialManager uecTrialManager = (UecTrialManager) ApplicationContextUtil
			.getBean("uecTrialManager");
	/**
	 * 外包人员基本信息对象
	 */
	private UecOutStaffInfo uecOutStaffInfo;
	private UecOutStaffInfo qryUecOutStaffInfo;

	/**
	 * 外包人员虚拟对象
	 */
	private UecOutStaffInfoVo uecOutStaffInfoVo;

	/**
	 * 任职信息
	 */
	private UecPsnjob qryUecPsnjob;
	/**
	 * 部门
	 */
	private UecOrgDept findUecOrgDept;

	/**
	 * 人员类别
	 */
	private UecBdPsncl uecBdPsncl;
	/**
	 * 人员类别
	 */
	private UecBdPsncl uecBdPsnclTree;
	/**
	 * 外包人员合同
	 */
	private UecOutStaffContract uecOutStaffContract = new UecOutStaffContract();

	/**
	 * 选择的组织
	 */
	private OrganizationRelationVo organization;
	/**
	 * 外包人员基本信息更新标志
	 */
	private boolean outStaffInfoUpdateFlag = false;

	private UecOrgOrgsManager uecOrgOrgsManager = (UecOrgOrgsManager) ApplicationContextUtil
			.getBean("uecOrgOrgsManager");

	private UecOrgDeptManager uecOrgDeptManager = (UecOrgDeptManager) ApplicationContextUtil
			.getBean("uecOrgDeptManager");

	private UecPsnjobManager uecPsnjobManager = (UecPsnjobManager) ApplicationContextUtil
			.getBean("uecPsnjobManager");

	private CustomFilesManager customFilesManager = (CustomFilesManager) ApplicationContextUtil
			.getBean("customFilesManager");

	private UecOutStaffContractManager uecOutStaffContractManager = (UecOutStaffContractManager) ApplicationContextUtil
			.getBean("uecOutStaffContractManager");

	@Getter
	@Setter
	private IPortletInfoProvider portletInfoProvider;

	public OutStaffLeaveApplyListboxExt() {
		Executions.createComponents(OUT_STAFF_LEAVE_APPLY_LISTBOX_EXT_ZUL,
				this, null);
		Components.wireVariables(this, bean);
		Components.addForwards(this, this, '$');

		this.bean.getOutStaffPkDept().addForward("onGetOrganization", this,
				"onGetOrganizationResponse");
		this.bean.getOutPsncl().addForward("onGetBdPsncl", this, "onGetBdPsnclResponse");
	}

	/**
	 * 界面初始化
	 */
	public void onCreate() {
		bandListbox();
	}

	/**
	 * 监听人员类别组织树
	 */
	public void onGetBdPsnclResponse(final ForwardEvent event) {
		if (event.getOrigin().getData() != null) {
			uecBdPsnclTree = (UecBdPsncl) event.getOrigin().getData();
		}
	}
	/**
	 * 监听组织树插件抛出的事件
	 * 
	 * @param event
	 */
	public void onGetOrganizationResponse(final ForwardEvent event) {
		if (event.getOrigin().getData() != null) {
			organization = (OrganizationRelationVo) event.getOrigin().getData();
			if ("ORG".equals(organization.getOrgType())) {
				ZkUtil.showError("转正后部门选项请选择到部门层级!", "错误提示");
				bean.getOutStaffPkDept().setValue(null);
				bean.getPkHrorg().setValue(null);
				return;
			} else {
				// 根据部门主键：pkorg，找到该部门所在的公司
				findUecOrgDept = new UecOrgDept();
				findUecOrgDept.setPkDept(organization.getOrg());
				findUecOrgDept = uecOrgDeptManager
						.findUecOrgDeptByOrgDept(findUecOrgDept);
				
				String orgNametemp="";
				if (null != findUecOrgDept) {
					String code = PlatformUtil.getCurrentUser().getScreenName().toUpperCase();
					String uecOrgOrgsNameByPkOrg = uecOrgOrgsManager.getUecOrgOrgsNameByPkOrg(findUecOrgDept.getPkOrg());
					orgNametemp = PermissionUtil.getManagerOrg();
					String[] orgnamelist= orgNametemp.split(",");
					boolean   temp=false;
					if(code.startsWith("W2019")) {
						      for(int i=0;i<orgnamelist.length;i++) {
								if( !uecOrgOrgsNameByPkOrg.contains(orgnamelist[i])) {
								  temp=true;
								  break;
								}
						}
					}
					if(temp) {
						return;
					}	  
					bean.getPkHrorg().setValue(uecOrgOrgsNameByPkOrg);

				}
			}		
	}
}		
	/**
	 * 查询按钮 根据条件查询
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */
	public void onQuery() throws SuspendNotAllowedException, Exception {
		clearVariable();
		uecOutStaffInfoVo = new UecOutStaffInfoVo();
		/**
		 * 组织树Ext UecOrganizationTreeBandboxExt 组织树上有组织和部门 通过组织树获取组织或部门
		 */
		if (!StrUtil.isNullOrEmpty(bean.getOutStaffPkHrorg().getValue())) {
			// 组织类型：公司 or 部门
			String orgType = (String) bean.getOutStaffPkHrorg()
					.getOrganization().getOrgType();
			// 组织主键
			String pkorg = (String) bean.getOutStaffPkHrorg().getOrganization()
					.getOrg();
			String orgName = (String) bean.getOutStaffPkHrorg().getOrganization().getOrgName();
			if ("ORG".equals(orgType)) {
				// 公司
				//uecOutStaffInfoVo.setPkOrg(pkorg);
				 if("中国电信股份有限公司内蒙古分公司".equals(orgName)) {
			       		uecOutStaffInfoVo
			       		.setOrgName(null);
			       	}else if(orgName.endsWith("*")){
			       		uecOutStaffInfoVo
			       		.setOrgName(orgName);
			       	}else {
			       		uecOutStaffInfoVo.setPkOrg(pkorg);
			       	}
			}  else {
				// 部门
				uecOutStaffInfoVo.setPkDept(pkorg);
			}
		}
		uecOutStaffInfoVo.setStaffCode(bean.getOutStaffCode().getValue());
		uecOutStaffInfoVo.setStaffName(bean.getOutStaffName().getValue());
		uecOutStaffInfoVo.setIdNum(bean.getOutStaffIdNum().getValue());
		// 查询员工
		outStaffList();
	}

	/**
	 * 员工列表
	 * 
	 * @throws Exception
	 * @throws SuspendNotAllowedException
	 */

	public void outStaffList() throws SuspendNotAllowedException, Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("opType", "outStaffList");
		map.put("uecOutStaffInfoVo", uecOutStaffInfoVo);
		Window window = (Window) Executions.createComponents(
				UecOutStaffConstants.UEC_OUT_STAFF_LIST_ZUL, this, map);
		window.doModal();
		window.addEventListener("onOK", new EventListener() {
			@Override
			public void onEvent(Event event) throws Exception {
				if (event.getData() != null) {
					qryUecOutStaffInfo = (UecOutStaffInfo) event.getData();
					// 获取外包人员试用信息
					UecTrial qryUecTrial = UecTrial.newInstance();
					qryUecTrial.setStaffId(qryUecOutStaffInfo.getOutStaffId());
					qryUecTrial
							.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
					qryUecTrial = uecTrialManager.findUecTrial(qryUecTrial);
					if (null == qryUecTrial) {
						ZkUtil.showError("此人未入职,请先执行入职操作", "温馨提示");
						return;
					}
					// 获取外包人员合同信息
					UecOutStaffContract qyrUecOutStaffContract = UecOutStaffContract
							.newInstance();
					qyrUecOutStaffContract = uecOutStaffContractManager
							.qryUecOutStaffContractByUecOutStaffInfo(uecOutStaffInfo);
					if (null != qyrUecOutStaffContract) {
						ZkUtil.showError("未查询到该人员的合同信息，请联系管理员！", "温馨提示");
						return;
					}
					// 获取外包人员任职信息
					qryUecPsnjob = new UecPsnjob();
					qryUecPsnjob.setStaffId(qryUecOutStaffInfo.getOutStaffId());
					qryUecPsnjob
							.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
					qryUecPsnjob = uecPsnjobManager.findUecPsnjob(qryUecPsnjob);
					if (null != qryUecPsnjob) {
						bean.getPsnName().setValue(
								qryUecOutStaffInfo.getPsnName());
						bean.getPsnCode().setValue(
								qryUecOutStaffInfo.getPsnCode());
						// 组织
						bean.getOrgName().setValue(
								uecOrgOrgsManager
										.getUecOrgOrgsNameByPkOrg(qryUecPsnjob
												.getPkOrg()));
						bean.getPkHrorg().setValue(
								uecOrgOrgsManager
										.getUecOrgOrgsNameByPkOrg(qryUecPsnjob
												.getPkOrg()));
						// 部门
						bean.getDeptName().setValue(
								uecOrgDeptManager
										.getUecOrgDeptNameByPkDept(qryUecPsnjob
												.getPkDept()));
						bean.getOutStaffPkDept().setValue(
								uecOrgDeptManager
										.getUecOrgDeptNameByPkDept(qryUecPsnjob
												.getPkDept()));

						// 人员类别
						uecBdPsncl = new UecBdPsncl();
						uecBdPsncl.setPkPsncl(qryUecPsnjob.getPkPsncl());
						uecBdPsncl = customFilesManager
								.findUecUecBdPsnclByUecBdPsncl(uecBdPsncl);
						if (!StrUtil.isNullOrEmpty(uecBdPsncl)) {
							bean.getPsnclName().setValue(uecBdPsncl.getName());
						}

						uecOutStaffInfo = qryUecOutStaffInfo;
					} else {
						ZkUtil.showInformation("此人任职信息为空", "温馨提示");
					}
				}
			}
		});
	}

	/**
	 * 离职申请流程发起按钮
	 * 
	 * @throws Exception
	 */
	public void onLaunchLeaveApply() throws Exception {
		if (null == uecOutStaffInfo || null == uecOutStaffInfo.getOutStaffId()) {
			ZkUtil.showError("未获取人员！", "错误提示");
			return;
		}
		// 数据校验
		String msg = this.checkUacStaffData();
		if (null != msg) {
			Messagebox.show(msg);
			return;
		}
		// 获取登录用户
		String currentName = "";
		if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
			ZkUtil.showError("当前登录用户已经失效，请重新登录系统", "错误提示");
			return;
		} else {
			currentName = PlatformUtil.getCurrentUser().getScreenName();
		}
		// 获取离职原因
		qryUecPsnjob.setTrnsreason((String) bean.getTrnsReason()
				.getSelectedItem().getValue());
		// 获取离职业务类型，TRNSTYPE
		qryUecPsnjob.setTrnstype((String) bean.getTrnsType().getSelectedItem()
				.getValue());
		// 获取人员类别
		if(null != uecBdPsnclTree) {
			String pkpsncl = uecBdPsnclTree.getPkPsncl();
			qryUecPsnjob.setPkPsncl(pkpsncl);
		}
		// 是否结束：是
		qryUecPsnjob.setEndflag("Y");
		// 人员状态
		qryUecPsnjob.setPoststat("N");
		/**
		 * 生效日期：为任职信息离职的结束日期
		 */
		Date effectDate = this.bean.getEffectDate().getValue();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String enddate = sdf.format(effectDate);
		/**
		 * 判断离职的生效日期是否在外包人员合同的日期后
		 */
		uecOutStaffContract = uecOutStaffContractManager
				.qryUecOutStaffContractByUecOutStaffInfo(uecOutStaffInfo);
		if (StrUtil.isNullOrEmpty(effectDate)) {
			ZkUtil.showError("生效日期为空!", "错误提示");
			return;
		}
		if (StrUtil.isNullOrEmpty(uecOutStaffContract.getCtBeginDate())) {
			ZkUtil.showError("外包合同开始日期为空!", "错误提示");
			return;
		}
		if (StrUtil.isNullOrEmpty(uecOutStaffContract.getCtEndDate())) {
			ZkUtil.showError("外包合同结束日期为空!", "错误提示");
			return;
		}
		/*boolean belongCalendar = DateUtil.compareDate(enddate,
				uecOutStaffContract.getCtEndDate());
		if (!belongCalendar) {
			ZkUtil.showError("合同未解除，请先前往MSS系统解除合同！", "温馨提示");
			return;
		}*/
		qryUecPsnjob.setEnddate(enddate);
		// 获取修改人信息
		qryUecPsnjob.setModifier(currentName);
		// 获取修改时间
		qryUecPsnjob.setModifiedtime(DateUtil.getCurrenDate());
		// 离职申请
		if (null != qryUecPsnjob) {
			// 如果触发了事件
			if (null != findUecOrgDept) {
				// 更新人员基本信息中的组织
				if (!uecOutStaffInfo.getPkHrorg().equals(
						findUecOrgDept.getPkOrg())) {
					uecOutStaffInfo.setPkHrorg(findUecOrgDept.getPkOrg());
					uecOutStaffInfo.setModifier(currentName);
					uecOutStaffInfo.setModifiedTime(DateUtil.getCurrenDate());
					outStaffInfoUpdateFlag = true;
				} else {
					outStaffInfoUpdateFlag = false;
				}
				// 组织、部门
				if (null != findUecOrgDept) {
					qryUecPsnjob.setPkDept(findUecOrgDept.getPkDept());
					qryUecPsnjob.setPkHrorg(findUecOrgDept.getPkOrg());
				}
			}
		}
		// 发起流程
		if (ApprovalUtil.getActivityFlag()) {

			String procDefId = ApprovalConstants.OUT_STAFF_RETIRE_PROC_DEF_ID;

			// 判断该人员是否在审状态，如果是在审状态不允许再次发起此流程
			boolean isOnApproval = ApprovalUtil.isOnApproval(procDefId,
					uecOutStaffInfo.getOutStaffId());
			if (isOnApproval) {
				ZkUtil.showError("在审状态不允许发起！", "错误提示");
				return;
			}
			if (StrUtil.isNullOrEmpty(PlatformUtil.getCurrentUser())) {
				ZkUtil.showError("当前登录用户不存在!", "错误提示");
				return;
			}
			/**
			 * 数据入库 修改uec_psnjob中一条数据
			 */
			Long outStaffIdHis = uecOutStaffInfo.getOutStaffId();
			Long outStaffId = outStaffIdHis;
			Long psnjobIdHis = qryUecPsnjob.getPsnjobId();

			qryUecPsnjob.setStaffId(outStaffIdHis);
			qryUecPsnjob.setNmStaffType(BaseUnitConstants.NM_OUT_STAFF_TYPE);
			qryUecPsnjob.addStatusCdIS3();
			Long psnjobIdModify = qryUecPsnjob.getPsnjobId();

			String formTheme = "盟市外包人员离退流程";

			String startFlowJson = "{" + "formTheme: '" + formTheme + "',"
					+ " formContent: '离职人员:" + uecOutStaffInfo.getPsnName()
					+ "'," + " procDefId: '" + procDefId + "',"
					+ " urgent: '1'," + " atiActCategoryId: '"
					+ ApprovalConstants.LEAVE_CATEGORY_ID + "',"
					+ " procDefKey: '" + ApprovalUtil.OUT_STAFF_RETIRE + "',"
					+ " formSender: '" + currentName + "'," + " primaryId: '{"
					+ "uec_out_staff_info_his:" + outStaffIdHis
					+ ",uec_out_staff_info:" + outStaffId + ",uec_psnjob_his:"
					+ psnjobIdHis + ",uec_psnjob_modi:" + psnjobIdModify + "'}";

			// ZkUtil.showInformation("离职申请流程已发起", "温馨提示");
			String procInstId = null;
			try {
				procInstId = ApprovalUtil.startApproval(startFlowJson);
			} catch (Exception e) {
				// 流程发起失败 数据改为失效
				qryUecPsnjob.removeOnly();
				onReset();
				ZkUtil.showError("流程发起失败！", "错误提示");
				e.printStackTrace();
			}
			if (StrUtil.isNullOrEmpty(procInstId)) {
				qryUecPsnjob.removeOnly();
				onReset();
				ZkUtil.showError("流程发起失败！", "错误提示");
				return;
			}
			// 第一审批人如果是发起人直接到人力审批环节
			ApprovalUtil.isCurrentAssignNames(procInstId);

			ApprovalUtil.showNextAssignee(procInstId, formTheme);
			onReset();
		} else {
			if (outStaffInfoUpdateFlag) {
				uecOutStaffInfo.updateOnly();
			}
			// 直接更新数据
			qryUecPsnjob.updateOnly();
			ZkUtil.showInformation("数据保存成功", "温馨提示");
			onReset();
		}

	}

	/**
	 * 检测填入的参数是否为空
	 */
	public String checkUacStaffData() {
		if (StrUtil.isNullOrEmpty(bean.getEffectDate().getValue())) {
			return "请选择生效日期";
		} else if (StrUtil.isNullOrEmpty(bean.getOutPsncl().getValue())) {
			return "请选择人员类别";
		} else if (StrUtil.isNullOrEmpty(bean.getTrnsType().getSelectedItem()
				.getValue())) {
			return "请选择离职业务类型";
		} else if (StrUtil.isNullOrEmpty(bean.getTrnsReason().getSelectedItem()
				.getValue())) {
			return "请选择离职原因";
		}
		return null;
	}

	/**
	 * 清除变量
	 */
	public void clearVariable() {
		uecOutStaffInfo = null;
		qryUecOutStaffInfo = null;
		uecOutStaffInfoVo = null;
	}

	/**
	 * 重置按钮
	 */
	public void onReset() {
		clearVariable();
		PubUtil.clearComponent(this);
	}

	/**
	 * 绑定Listbox
	 */
	public void bandListbox() {
		// 人员类别--PSNCL_PK_ORG
		ListboxUtils.rendererForEdit(bean.getPkPsncl(),
				NodeVoUtil.getDictionariesPsncl(UecConstants.PSNCL_PK_ORG));
		// 离职原因
		List<NodeVo> nodeVotrnsReasonList = new ArrayList<NodeVo>();
		String[][] trnsReason = { { "1001A1100000000012ZO", "终止劳动合同" },
				{ "1001A1100000000012ZR", "主动离职" },
				{ "1001A1100000000012ZS", "非主动离职" },
				{ "1001A1100000000012ZQ", "企业内部调动" },
				{ "1001A1100000001KKMYR", "离退休、退职" }, };
		for (int i = 0; i < trnsReason.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(trnsReason[i][j]);
				nodeVo.setName(trnsReason[i][j + 1]);
			}
			nodeVotrnsReasonList.add(nodeVo);
		}
		ListboxUtils
				.rendererForEdit(bean.getTrnsReason(), nodeVotrnsReasonList);

		// 离职业务类型--异动类型TRNSTYPE
		List<NodeVo> nodeVotrnstypeList = new ArrayList<NodeVo>();
		String[][] trnstype = { { "1002Z710000000008GSV", "离退休" },
				{ "1002Z710000000008GSW", "退职" },
				{ "1002Z710000000008GSX", "组织调动-到实业" },
				{ "1002Z710000000008PAW", "企业解除合同" },
				{ "1002Z710000000008GSZ", "员工解除合同" },
				{ "1001A110000000000R1W", "企业终止合同" },
				{ "1001A110000000000R1X", "员工终止合同" },
				{ "1001A110000000000R1Y", "死亡（在职）" },
				{ "1001A110000000000R1Z", "调出集团（不含成建制）" },
				{ "1001A110000000000R20", "成建制划出" },
				{ "1001A110000000000R21", "派遣制员工离职" },
				{ "1001A110000000000R22", "组织调动-到控股参股" },
				{ "1001A110000000000R24", "有偿协商解除合同" },
				{ "1001A110000000000R23", "有偿协商解除合同" } };
		for (int i = 0; i < trnstype.length; i++) {
			NodeVo nodeVo = new NodeVo();
			for (int j = 0; j < 1; j++) {
				nodeVo.setId(trnstype[i][j]);
				nodeVo.setName(trnstype[i][j + 1]);
			}
			nodeVotrnstypeList.add(nodeVo);
		}
		ListboxUtils.rendererForEdit(bean.getTrnsType(), nodeVotrnstypeList);
	}

}
